<?php

namespace app\health\model;

use think\Model;

class HealthGoods extends Model
{
    // 表名
    protected $name = 'health_goods';
    // 定义时间戳字段名
    protected $createTime = 'add_time';
    protected $updateTime = 'upd_time';

    protected $append = [
        'picture',
        'is_enable_text'
    ];

    public const TAG_MAP = [
        1 => '火爆',
        2 => '折扣'
    ];

    public function getIsEnableTextAttr($val, $data)
    {
        return $data['is_enable'] == 1 ? '上架' : '下架';
    }

    /**
     * 获取封面图片地址
     * @param [type] $val
     * @param [type] $data
     * @Author 张旭鹏
     * @DateTime 2023-06-15
     */
    public function getPictureAttr($val, $data)
    {
        $image = $data['image'] ?? '';
        return $image ? cdnurl($image, true) : '';
    }


    /**
     * 关联商品规格
     * @Author 张旭鹏
     * @DateTime 2023-06-13
     */
    public function goodsAttr()
    {
        return $this->hasMany(HealthGoodsAttr::class, 'goods_id');
    }

    /**
     * 获取销售数量
     * @param [type] $val
     * @param [type] $data
     * @Author 张旭鹏
     * @DateTime 2023-06-13
     */
    public function getTotalSalesAttr($val, $data)
    {
        return $data['virtually_sales_total'] + $data['sales_total'];
    }

    /**
     * Undocumented function
     * @Author 张旭鹏
     * @DateTime 2023-06-21
     */
    public function category()
    {
        return $this->belongsTo(HealthGoodsCategory::class, 'category_id');
    }

    /**
     * 获取商品标签文本
     * @param [type] $val
     * @param [type] $data
     * @return string
     * @Author 张旭鹏
     * @DateTime 2023-07-13
     */
    public function getTagTextAttr($val, $data)
    {
        return self::TAG_MAP[$data['tag']] ?? '';
    }
}
